package SparseArray;

public class SparseArray {
    public static void main(String[] args) {
        int[][] orginArray = new int[11][11];
        orginArray[1][2]=1;
        orginArray[2][3]=2;
        orginArray[3][8]=2;

        System.out.println("原始数组~~~");
        for (int[] row:orginArray){
            for (int item:row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }

        //统计原始数组中的有效数据个数
        int num=0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if(orginArray[i][j]!=0){
                    num++;
                }
            }
        }

        //对稀疏数组的第一行进行初始化
        int[][] sparseArray = new int[num+1][3];
        sparseArray[0][0]=11;
        sparseArray[0][1]=11;
        sparseArray[0][2]=num;

        //对稀疏数组的剩下部分进行赋值
        int count=0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if(orginArray[i][j]!=0){
                    count++;
                    sparseArray[count][0]=i;
                    sparseArray[count][1]=j;
                    sparseArray[count][2]=orginArray[i][j];
                }
            }
        }

        System.out.println("稀疏数组~~~");
        for (int[] row:sparseArray){
            for (int item:row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }

        //恢复原始数组（不含数据）
        int[][] orginArray2 = new int[sparseArray[0][0]][sparseArray[0][1]];

        //恢复原始数组数据
        for (int i = 1; i < sparseArray.length ; i++) {
            orginArray2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }

        System.out.println("恢复后数组~~~");
        for (int[] row:orginArray2){
            for (int item:row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }


    }
}
